<script setup lang="ts">
import type { BasicClassValueField } from "@@/apis/basic-data/types"
import type { VxeGlobalRendererHandles } from "vxe-pc-ui"
import type { VxeTableDefines } from "vxe-table"
import { listStructField } from "@@/apis/basic-data/index"
import { BSDataTypeEnum, RecordTypeEnum } from "@@/constants/other-keys"
import { getRecordBaseValue } from "@@/utils/parseParamValue"
import { ElMessageBox } from "element-plus"
import { cloneDeep } from "lodash"
import { computed, defineProps, ref } from "vue"
import XEUtils from "xe-utils"
import "./EnumValueDownModal"

interface Props {
  params: VxeGlobalRendererHandles.RenderTableEditParams
}

const props = defineProps<Props>()
const row = ref<BasicClassValueField>(props.params.row)
const column = ref<VxeTableDefines.ColumnInfo>(props.params.column)
const modalVisible = ref<boolean>(false)
const loading = ref<boolean>(false)
const isLazy = ref<boolean | undefined>(false)
const valueDatas = ref<BasicClassValueField[]>([])
const typingValueTable = ref()

const showValue = computed(() => {
  let value = row.value && getRecordBaseValue(row.value)
  return value
})

function load() {
  if (row.value[column.value.field] == 0) {
    row.value[column.value.field] = null
  }
  if (row.value[column.value.field]) {
    isLazy.value = false
    setTimeout(() => {
      valueDatas.value = JSON.parse(row.value[column.value.field])
      typingValueTable.value.loadData(valueDatas.value)
    }, 300)
  } else {
    isLazy.value = true
    listStructField({ baseDataId: row.value.typeId }).then(({ data }) => {
      valueDatas.value = data

      function guid() {
        return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
          let r = Math.random() * 16 | 0
          let v = c == "x" ? r : (r & 0x3 | 0x8)
          return v.toString(16)
        })
      }
      XEUtils.arrayEach(valueDatas.value, (item, key) => {
        item.uuid = guid()
        item.children = []
        if (item.type == BSDataTypeEnum.Class && item.recordType == RecordTypeEnum.Base) {
          item.hasChild = true
        }
      })
    })
  }
}

function putuuid() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    let r = Math.random() * 16 | 0
    let v = c == "x" ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}
function loadChildrenMethod({ row }): Promise<BasicClassValueField[]> {
  return new Promise<BasicClassValueField[]>((resolve, reject) => {
    setTimeout(() => {
      if (row.recordType == RecordTypeEnum.Base) {
        listStructField({ baseDataId: row.typeId }).then(({ data }) => {
          XEUtils.arrayEach(data, (item, key) => {
            item.uuid = putuuid()
            item.children = []
            if (item.type === BSDataTypeEnum.Class && item.recordType == RecordTypeEnum.Base) {
              item.hasChild = true
            }
          })
          row.children = cloneDeep(data)
          typingValueTable.value.loadData(valueDatas.value)
          typingValueTable.value.toggleTreeExpand(row)
          resolve(data)
        })
      }
      resolve([])
    }, 500)
  })
}
function popupEvent() {
  modalVisible.value = true
  load()
}
function confirmEvent() {
  let { tableData } = typingValueTable.value.getTableData()
  row.value[column.value.field] = JSON.stringify(tableData)
  modalVisible.value = false
}
// 添加元素
async function addData(row: BasicClassValueField) {
  let Subdata: BasicClassValueField[] = []
  await listStructField({ baseDataId: row.typeId }).then(({ data }) => {
    Subdata = data
    XEUtils.arrayEach(Subdata, (item, key) => {
      if (item.type === "class" && item.recordType == RecordTypeEnum.Base) {
        item.uuid = getuuid()
        item.hasChild = true
      }
    })
  })
  function getuuid() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
      let r = Math.random() * 16 | 0
      let v = c == "x" ? r : (r & 0x3 | 0x8)
      return v.toString(16)
    })
  }
  function dataHandle(data: BasicClassValueField[], row: BasicClassValueField) {
    for (let j = 0; j < data.length; j++) {
      if (data[j].uuid == row.uuid) {
        let obj: BasicClassValueField = {
          uuid: getuuid(),
          elementName: "元素",
          elementIndex: data[j].children.length + 1,
          type: BSDataTypeEnum.Element,
          typeCode: "无",
          children: Subdata,
          hasChild: true,
          typeId: row.typeId,
          separator: row.separator,
          recordType: RecordTypeEnum.Base,
          establish: true
        }
        data[j].children.push(obj)
      } else if (data[j].children && data[j].children.length > 0) {
        dataHandle(data[j].children, row)
      }
    }
  }
  dataHandle(valueDatas.value, row)
  typingValueTable.value.loadData(valueDatas.value)
}
// 删除元素
async function deleteData(row: BasicClassValueField) {
  ElMessageBox.confirm(`是否确认删除？`, "提示", {
    customClass: "drawer-message-box",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    dataHandle(valueDatas.value, row)
    function dataHandle(data: BasicClassValueField[], row: BasicClassValueField) {
      for (let j = 0; j < data.length; j++) {
        if (data[j].uuid == row.uuid) {
          data.splice(j, 1)
        } else if (data[j].children && data[j].children.length > 0) {
          dataHandle(data[j].children, row)
        }
      }
    }
    typingValueTable.value.loadData(valueDatas.value)
  })
}
</script>

<template>
  <div class="typing-value-down-modal">
    <el-input class="edit-down-input" readonly v-model="showValue":title="showValue" @click="popupEvent">
      <template #suffix>
        <el-link class="edit-popup-button" type="primary" :underline="false" @click="popupEvent">
          获取
        </el-link>
      </template>
    </el-input>
    <el-drawer
      v-model="modalVisible"
      direction="rtl"
      size="800"
      :append-to-body="true"
    >
      <template #header>
        <h4>{{ `设置【 ${row.code} 】的值` }}</h4>
      </template>
      <template #default>
        <div class="drawer-body-lock">
          <div class="drawertable-content">
            <vxe-table class="drawer-table" ref="typingValueTable" height="auto" highlight-hover-row auto-resize show-overflow resizable keep-source :data="valueDatas" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" :tree-config="{ lazy: true, childrenField: 'children', hasChild: 'hasChild', loadMethod: loadChildrenMethod }">
              <vxe-table-column field="id" :visible="false" title="标识" />
              <vxe-table-column title="标识" tree-node>
                <template #default="{ row }">
                  {{ row.code ? row.code : row.elementName + row.elementIndex }}
                </template>
              </vxe-table-column>
              <vxe-table-column title="分类" width="100">
                <template #default="{ row }">
                  {{ row.type === BSDataTypeEnum.Base ? '基本类型' : row.type === BSDataTypeEnum.Enum ? '枚举' : row.type === BSDataTypeEnum.Element ? '元素' : '类' }}
                </template>
              </vxe-table-column>
              <vxe-table-column field="typeCode" title="数据类型" />
              <vxe-table-column field="value" title="值" width="180" :cell-render="{ name: 'EnumValueDownModal' }" formatter="formatValue" />
              <vxe-table-column title="操作" width="70">
                <template #default="{ row }">
                  <span v-if="row.recordType == RecordTypeEnum.Base" />
                  <el-link v-if="row.recordType == RecordTypeEnum.Array && row.type == BSDataTypeEnum.Class" :underline="false" type="primary" @click="addData(row)" title="添加元素">
                    <el-icon><Plus /></el-icon>
                  </el-link>
                  <el-link v-if="row.establish" type="danger" :underline="false" title="删除" @click="deleteData(row)">
                    <el-icon><Delete /></el-icon>
                  </el-link>
                </template>
              </vxe-table-column>
            </vxe-table>
          </div>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button plain @click="modalVisible = false">
            取 消
          </el-button>
          <el-button :loading="loading" type="primary" @click="confirmEvent">
            确 定
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
.drawertable-content {
  height: calc(100vh - 350px);
}

.typing-value-down-modal {
  display: flex;
  align-items: center;
}

.header {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}
</style>
